<template>
  <el-select
    :value="value"
    clearable
    filterable
    remote
    :multiple="multiple"
    reserve-keyword
    :placeholder="placeholder"
    :loading="loading"
    @change="updateValue">
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value"/>
  </el-select>
</template>
<script setup>
import {computed, onMounted, ref} from "vue";
import {getProductPage as getList} from "@/api/yz/product"

const props = defineProps({
  placeholder: {
    type: String,
    default: '请选择'
  },
  value: {
    type: [Array, String, Number],
    default: null
  },
  multiple: {
    type: Boolean,
    default: false
  }
})
// 备选专家
const list = ref([])
// 筛选专家方法
const loading = ref(false)
const remoteFilter = async (query) => {
  loading.value = true
  try {
    const res = await getList({
      pageNum: 1,
      pageSize: 100,
      name: query
    })
    list.value = res.list;
    console.log(res)
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}
// 页面加载时需要调用初始方法
onMounted(remoteFilter)
// 转换成el-select的备选项
const options = computed(() => {
  return list.value.map(item => {
    let label = item.name;
    return {
      label,
      value: Number.parseInt(item.id)
    }
  })
})
const emit = defineEmits(['update:value','change'])
// 更新选中的专家
const updateValue = (value) => {
  emit('input', value)
  // 找到对应专家
 const expert= list.value.find(item=>item.id===value);
  emit('change', expert)
}

</script>
